/**
 * @拨打电话
 * @param { 电话 } phone
 */
export function OpenPhone(phone) {
    return uni.makePhoneCall({
        phoneNumber: phone
    })
}

/**
 * @copy内容
 */
export function getCopy(proxy, text) {
    return uni.setClipboardData({
        data: text,
        showToast: false,
        success: function () {
            proxy.$Toast(proxy, "复制成功！")
        }
    });
}

/**
 * APP端 图片压缩
 * @param img {图片url}
 */
export function compressImg(imgUrl) {
    return new Promise((resolve, reject) => {
        // var localPath = plus.io.convertAbsoluteFileSystem(imgUrl);
        //通过URL参数获取目录对象或文件对象
        plus.io.resolveLocalFileSystemURL(imgUrl, (entry) => {
            // 可通过entry对象操作图片
            entry.file((file) => {
                console.log('压缩前图片信息:' + JSON.stringify(file));
                //如果大于500Kb进行压缩
                if (file.size > 524288) {
                    // 5+ plus.zip.compressImage 了解一下，有详细的示例
                    plus.zip.compressImage({
                        src: imgUrl, //src: 压缩原始图片的路径
                        dst: imgUrl.replace('.png', 'compress.png').replace('.PNG', 'compress.PNG').replace('.jpg', 'compress.jpg')
                            .replace('.JPG', 'compress.JPG'),//dst: (String 类型 )压缩转换目标图片的路径，这里先在后面原始名后面加一个compress区分一下
                        width: '40%',  //width,height: (String 类型 )缩放图片的宽度,高度
                        height: '40%',
                        quality: 10, //quality: (Number 类型 )压缩图片的质量
                        overwrite: true, //overwrite: (Boolean 类型 )覆盖生成新文件
                        // format:'jpg'   //format: (String 类型 )压缩转换后的图片格式
                    }, (event) => {
                        console.log('压缩后图片信息:' + JSON.stringify(event));
                        let newImg = event.target;
                        //返回新的图片地址，在uploadFile之前接收
                        resolve(newImg);
                    }, function (err) {
                        // console.log('Resolve file URL failed: ' + err.message);
                        reject(err.message);
                    });
                }
                //else小于500kb跳过压缩，直接返回
                else {
                    resolve(imgUrl);
                }
            });
        }, (err) => {
            reject(err.message);
            console.log('compressImg URL failed: ' + err.message);
        });
    })
}


/**
 * H5端图片压缩
 *  参数说明：
 *  imgSrc 图片url
 *  scale缩放比例 0-1
 *  type 返回图片类型  默认blob
 *  callback 回调设置返回值
 */
export function translate(imgSrc, scale, type, callback) {
    var img = new Image();
    img.src = imgSrc;
    img.onload = function () {
        var that = this;
        var h = that.height; // 默认按比例压缩
        var w = that.width;
        var canvas = document.createElement('canvas');
        var ctx = canvas.getContext('2d');
        var width = document.createAttribute("width");
        width.nodeValue = w;
        var height = document.createAttribute("height");
        height.nodeValue = h;
        canvas.setAttributeNode(width);
        canvas.setAttributeNode(height);
        ctx.drawImage(that, 0, 0, w, h);
        var base64 = canvas.toDataURL('image/jpeg', scale);//压缩比例
        canvas = null;
        if (type == 'base64') {
            callback(base64);
        } else {
            var blob = base64ToBlob(base64);
            var blobUrl = window.URL.createObjectURL(blob);//blob地址
            callback(blobUrl);
        }
    }
}

/**
 * base转Blob
 */
export function base64ToBlob(base64) {
    var arr = base64.split(','),
        mime = arr[0].match(/:(.*?);/)[1],
        bstr = atob(arr[1]),
        n = bstr.length,
        u8arr = new Uint8Array(n);
    while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
    }
    return new Blob([u8arr], {
        type: mime
    });
}

/**
 * 打开app系统设置
 */
export function confirm() {
    let port = uni.getSystemInfoSync().platform
    if (port == "android") {
        var Intent = plus.android.importClass("android.content.Intent");
        var Settings = plus.android.importClass("android.provider.Settings");
        var Uri = plus.android.importClass("android.net.Uri");
        var mainActivity = plus.android.runtimeMainActivity();
        var intent = new Intent();
        intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
        var uri = Uri.fromParts("package", mainActivity.getPackageName(), null);
        intent.setData(uri);
        mainActivity.startActivity(intent);
    } else {
        var UIApplication = plus.ios.import("UIApplication");
        var application2 = UIApplication.sharedApplication();
        var NSURL2 = plus.ios.import("NSURL");
        // var setting2 = NSURL2.URLWithString("prefs:root=LOCATION_SERVICES");
        var setting2 = NSURL2.URLWithString("app-settings:");
        application2.openURL(setting2);
        plus.ios.deleteObject(setting2);
        plus.ios.deleteObject(NSURL2);
        plus.ios.deleteObject(application2);
    }
}

/**
 * 跳转到手机系统定位服务页面
 */
export function goSystemPositioningService() {
    if (port == "android") {
        var context = plus.android.importClass("android.content.Context");
        var locationManager = plus.android.importClass("android.location.LocationManager");
        var main = plus.android.runtimeMainActivity();
        var mainSvr = main.getSystemService(context.LOCATION_SERVICE);
        var Intent = plus.android.importClass('android.content.Intent');
        var Settings = plus.android.importClass('android.provider.Settings');
        var intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
        main.startActivity(intent); // 打开系统设置GPS服务页面
    } else {
        plus.runtime.openURL("app-settings://");
    }
}

/**
 * 保存两位小数
 * @param x
 * @returns {string}
 */
export function toDecimal(num) {
    var f = 0;
    //判断是否是字符串类型
    if (typeof (num) == "string") {
        if (num != null && num != '') {
            f = parseFloat(num);
        }
    } else {
        f = num;
    }
    f = f.toFixed(2);
    return f;
}

/**
 * 保存1位小数
 */
export function toDecimal1(num) {
    var f = 0;
    //判断是否是字符串类型
    if (typeof (num) == "string") {
        if (num != null && num != '') {
            f = parseFloat(num);
        }
    } else {
        f = num;
    }
    f = f.toFixed(1);
    return f;
}

/**
 * 微信小程序打开地图
 * @param proxy
 */
const wxOpenSetting = (proxy) => {
    // #ifdef MP-WEIXIN
    wx.openSetting({
        success: function (settingdata) {
            if (settingdata.authSetting['scope.userLocation']) {
                // 用户已经同意授权，再次尝试获取位置信息
                let addressLocation = ""
                uni.getLocation({
                    type: 'gcj02',
                    accuracy: 'best',
                    isHighAccuracy: true,
                    success: function (res) {
                        console.log('位置服务授权成功：', res);
                        addressLocation = res.longitude + ',' + res.latitude
                        // $addressHttp.getUserAddress({
                        //     location: addressLocation
                        // }, proxy).then(res => {
                        //     if (res.code == 0) {
                        //         // 存储当前所在地址
                        //         let data = {
                        //             "name": res.data.pois[0].name,
                        //             "location": addressLocation
                        //         }
                        //         uni.setStorageSync('address', data)
                        //     }
                        // })
                    },
                    fail: function (err) {
                        console.log("getLocation err = ", err)
                    }
                });
            } else {
                // 用户拒绝授权，可以在这里做相应的提示或处理
                wxOpenSetting(proxy)
                proxy.$Toast(proxy,'拒绝获取定位将影响功能正常使用！', "error");
            }
        },
        fail: function (err) {
            // 打开设置页面失败，可以在这里做相应的提示或处理
        }
    });
    // #endif
}